import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Table,
    Button,
    Card,
    Col,
    Divider,
    Input,
    Row,
    Select,
    Modal,
    DatePicker,
    Upload,
    message,
    Popconfirm,
    Tooltip,
    Dropdown,
    Menu,
} from 'antd';
import { UploadOutlined, DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const FormItem = Form.Item;
const { Option } = Select;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    logisCenterBatchList: any;
    INITINFO: any;
    loading: boolean;
    screen: string;
}

interface TableListState {
    current: number;
    pageSize: number | undefined;
    formValues: any;
    batchInfo: any;
    importDialog: boolean;
    fileList: any;
    rowId: number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
    logisCenterBatchList,
    common: { INITINFO },
    global: { screen },
    loading,
}: any) => ({
    logisCenterBatchList,
    INITINFO,
    screen,
    loading: loading.effects['logisCenterBatchList/fetch'],
}))

class TableList extends React.Component<TableListProps, TableListState> {
    columns: any = [
        {
            title: '物流中心',
            dataIndex: 'logisName',
            width: 120,
            render: (text: any, record: any) => (
                <Tooltip title={text}>
                    <div className="wordOmit nameLink" onClick={() => this.handleShowBatch(record.id)}>
                        {text}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '快递公司',
            dataIndex: 'expressName',
            width: 80,
            render: (text: any) => (
                <Tooltip title={text}>
                    <div className="wordOmit">{text}</div>
                </Tooltip>
            ),
        },
        {
            title: '批次日期',
            dataIndex: 'batchDate',
            width: 100,
        },
        {
            title: '批次号',
            dataIndex: 'seqNo',
            width: 80,
            render: (text: number) => `第${text}批`,
        },
        {
            title: '接驳总数(件)',
            dataIndex: 'scanCount',
            width: 100,
            render: (text: number) => `接驳订单(${text})`,
        },
        {
            title: '入库总数(件)',
            dataIndex: 'deliveredCount',
            width: 100,
        },
        {
            title: '到付金额(元)',
            dataIndex: 'paymentAmount',
            width: 100,
            render: (text: number) => text / 100,
        },
        {
            title: '状态',
            dataIndex: 'statusName',
            width: 60,
            render: (text: string) => text || '--',
        },
        {
            title: '操作',
            width: 130,
            dataIndex: 'id',
            fixed: 'right',
            render: (id: any, record: any) => (
                <>
                    <Popconfirm
                        title="确认开启？"
                        okText="确认"
                        cancelText="取消"
                        className="operLink"
                        onConfirm={() => this.handleOpenBatch(id)}
                    >
                        开启
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Popconfirm
                        title="确认禁用？"
                        okText="确认"
                        cancelText="取消"
                        className="operLink"
                        onConfirm={() => this.handleCloseBatch(id)}
                    >
                        禁用
                    </Popconfirm>
                    <Divider type="vertical" />
                    <Dropdown arrow overlay={() => this.menu(record)}>
                        <span className="operLink">
                            更多 <DownOutlined />
                        </span>
                    </Dropdown>
                </>
            ),
        },
    ];

    state: TableListState = {
        current: 1,
        pageSize: 20,
        formValues: {},
        batchInfo: {},
        importDialog: false,
        fileList: [],
        rowId: 0,
    };

    static getDerivedStateFromProps(props: any, state: any) {
        const { search } = props.location;
        const query = qs.parse(search, { ignoreQueryPrefix: true });
        const { page, psize, ...formValues } = query;

        return {
            ...state,
            formValues,
            current: Number(page) || 1,
            pageSize: Number(psize) || 20,
        };
    }

    componentDidMount() {
        this.setFieldsValue();

        const { logisCenterBatchList: { data } } = this.props;
        if (data?.list?.length) return;

        this.fetchLogisList();
        this.fetchExpressList();
        this.fetchDeliveryList();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { formValues, current, pageSize } = this.state;
        if (!_.isEqual(formValues, prevState.formValues)
            || current !== prevState.current
            || pageSize !== prevState.pageSize
        ) {
            this.setFieldsValue();
            this.fetchDeliveryList();
        }
    }

    // 设置表单值
    setFieldsValue = () => {
        const { formValues: { batchDate, ...others } } = this.state;
        if (batchDate) {
            others.batchDate = moment(batchDate);
        } else {
            others.batchDate = moment();
        }

        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(others);
    };

    // 获取物流中心列表
    fetchLogisList = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'common/fetchLogisList',
        });
    };

    // 获取校园小区列表
    fetchExpressList = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'common/fetchExpressList' });
    };

    // 获取数据
    fetchDeliveryList = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterBatchList/fetch',
            payload: this.getQueryParams(),
        });
    };

    // 获取查询参数
    getQueryParams = () => {
        const {
            formValues,
            current: pageIndex,
            pageSize,
        } = this.state;

        const params = { ...formValues, pageIndex, pageSize };
        if (!params.batchDate) {
            params.batchDate = moment().format('YYYY-MM-DD');
        }

        return params;
    };

    menu = (record: any) => (
        <Menu>
            <Menu.Item
                className="operLink"
                onClick={() => this.handleShowBatch(record.id)}
            >
                详情
            </Menu.Item>
            <Menu.Item
                className="operLink"
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => this.handlePrintCode(record)}
            >
                打印接驳订单
            </Menu.Item>
        </Menu>
    );

    /**
     * 查询
     */
    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();

        const { form: { validateFields } } = this.props;
        validateFields((err, fieldsValue) => {
            if (err) return;

            if (fieldsValue.batchDate) {
                fieldsValue.batchDate = moment(fieldsValue.batchDate).format('YYYY-MM-DD');
            }

            const query = { page: 1, ...fieldsValue };
            const { dispatch } = this.props;
            addTab(dispatch, {
                name: '接驳管理',
                url: `${pathname}?${qs.stringify(query)}`,
                isTopMenu: true,
            });
        });
    };

    /**
     * 重置
     */
    handleReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '接驳管理',
            url: pathname,
            isTopMenu: true,
        });
    };

    /**
     * 打开批量导入
     */
    handleOpenBatchImport = () => this.setState({ importDialog: true });

    /**
     * 关闭批量导入
     */
    handleCloseBatchImport = () => this.setState({ importDialog: false });

    /**
     * 批量导入接驳明细
     */
    handleBatchImport = () => {
        const { batchInfo, fileList } = this.state;
        if (!batchInfo.logisId) {
            message.error('请选择物流中心！');
            return;
        }

        if (!batchInfo.expressId) {
            message.error('请选择快递公司！');
            return;
        }

        if (!fileList.length) {
            message.error('请上传文件！');
            return;
        }

        [batchInfo.file] = [fileList[0].originFileObj];

        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterBatchList/import',
            payload: {
                query: this.getQueryParams(),
                params: batchInfo,
            },
        });

        this.handleCloseBatchImport();
    };

    /**
     * 查看详情
     */
    handleShowBatch = (id: number) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `查看${id}`,
            url: `${pathname}/detail?id=${id}`,
        });
    };

    /**
     * 开启批次
     */
    handleOpenBatch = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterBatchList/open',
            payload: {
                query: this.getQueryParams(),
                params: { id },
            },
        });
    };

    /**
     * 关闭批次
     */
    handleCloseBatch = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterBatchList/close',
            payload: {
                query: this.getQueryParams(),
                params: { id },
            },
        });
    };

    /**
     * 打印运单条形码
     */
    handlePrintCode = (record: any = {}) => {
        const { dispatch } = this.props;
        let exportUrl = '';

        Object.keys(record).forEach((key: any) => {
            exportUrl += `${key}=${record[key]}&`;
        });

        exportUrl = exportUrl.substring(0, exportUrl.length - 1);

        addTab(dispatch, {
            name: `${record.logisName}接驳明细单`,
            url: `/logisCenter/batch/list/print?${exportUrl}`,
        });
    };

    /**
     * 选择物流中心
     */
    handleChangeLogis = (value: string) => {
        const { batchInfo } = this.state;
        batchInfo.logisId = value;
        this.setState({ batchInfo });
    };

    /**
     * 选择快递公司
     */
    handleChangeExpress = (value: string) => {
        const { batchInfo } = this.state;
        batchInfo.expressId = value;
        this.setState({ batchInfo });
    };

    // 分页
    onSelectChange = (page: number, psize: number | undefined) => {
        const { formValues } = this.state;
        const query = { ...formValues, page, psize };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '接驳管理',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    handlePreview = async (file: any) => {
        window.open(file.url);
    };

    handleUpload = ({ file, fileList }: any) => {
        if (fileList.length > 0) {
            fileList[fileList.length - 1].name = '接驳文件';
        }
        const newFileList = fileList.length <= 0
            ? []
            : [fileList[fileList.length - 1]];
        this.setState({ fileList: newFileList });
    };

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    // 渲染查询表单
    renderSearchFormElem = () => {
        const {
            form: { getFieldDecorator },
            INITINFO: { expressList, logisList },
        } = this.props;

        return (
            <Form onSubmit={this.handleSearch} className="tableListForm">
                <Row gutter={12}>
                    <Col md={6} sm={24}>
                        <FormItem label="物流中心" colon={false}>
                            {getFieldDecorator('logisId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {logisList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="快递公司" colon={false}>
                            {getFieldDecorator('expressId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {expressList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="批次日期" colon={false}>
                            {getFieldDecorator('batchDate')(
                                <DatePicker
                                    disabledDate={timeLimit}
                                    placeholder="请选择日期"
                                    style={{ width: '100%' }}
                                />,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="批次编号" colon={false}>
                            {getFieldDecorator('seqNo')(
                                <Input
                                    allowClear
                                    type="number"
                                    placeholder="请输入"
                                    style={{ width: '100%' }}
                                />,
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col md={24} sm={24}>
                        <div className="flexFeView" style={{ paddingBottom: 8 }}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="smallButton"
                            >
                                查询
                            </Button>
                            <Button
                                type="primary"
                                className="addButton smallButton marginL16"
                                onClick={this.handleReset}
                            >
                                重置
                            </Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        );
    };

    // 渲染批量导入
    renderImportModalElem = () => {
        const { importDialog, batchInfo, fileList } = this.state;
        const { INITINFO: { logisList, expressList } } = this.props;

        return (
            <Modal
                title="批量导入接驳明细"
                visible={importDialog}
                onOk={this.handleBatchImport}
                onCancel={this.handleCloseBatchImport}
            >
                <Form className="tableListForm">
                    <Row>
                        <Col md={20} sm={20}>
                            <Form.Item label="物流中心" colon={false}>
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    value={batchInfo.logisId}
                                    onChange={this.handleChangeLogis}
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {logisList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col md={20} sm={20}>
                            <Form.Item label="快递公司" colon={false}>
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    value={batchInfo.expressId}
                                    onChange={this.handleChangeExpress}
                                    filterOption={(input: any, option: any) => option.props.children
                                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {expressList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col md={20} sm={20}>
                            <Form.Item label="请选择文件" colon={false}>
                                <Upload
                                    accept=".xls,.xlsx"
                                    fileList={fileList}
                                    beforeUpload={() => false}
                                    onPreview={this.handlePreview}
                                    onChange={this.handleUpload}
                                >
                                    <Button
                                        type="primary"
                                        style={{ fontSize: 12 }}
                                        size="small"
                                        ghost
                                    >
                                        <UploadOutlined />
                                        上传文件
                                    </Button>
                                </Upload>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        );
    };

    render() {
        const { current, pageSize } = this.state;
        const {
            logisCenterBatchList: { data },
            loading,
            screen,
        } = this.props;

        const pagination = data
            ? {
                total: data ? data.count : 0,
                pageSize,
                current: current || 1,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: () => `共${data.count || 0}条数据`,
                onChange: this.onSelectChange,
                onShowSizeChange: this.onSelectChange,
            }
            : {};

        if (screen === 'sm' || screen === 'lg') {
            delete this.columns[this.columns.length - 1].fixed;
        } else if (screen === 'md') {
            this.columns[this.columns.length - 1].fixed = 'right';
        }

        return (
            <>
                <PageHeader />

                <Card bordered={false} className="searchForm">
                    {this.renderSearchFormElem()}
                </Card>

                <Card bordered={false} className="tableList">
                    <div className="tableBtns">
                        <Button
                            type="primary"
                            size="small"
                            className="smallButton"
                            onClick={this.handleOpenBatchImport}
                        >
                            批量导入接驳
                        </Button>
                    </div>
                    <Table
                        rowKey="id"
                        tableLayout="fixed"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={data.list || []}
                        pagination={pagination}
                        loading={loading}
                        scroll={{ x: 1200 }}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />
                </Card>

                {this.renderImportModalElem()}
            </>
        );
    }
}

export default Form.create<TableListProps>()(TableList);
